import os
import getpass
import subprocess
import platform
from datetime import datetime
from colorama import init, Fore, Style
import psutil,netifaces
# from kyptools.src.passwd import myown_passwd

filename = "passwd.py"  
current_directory = os.path.dirname(os.path.realpath(__file__))  # 获取当前文件所在的文件夹路径
file_path = os.path.join(current_directory, filename)  # 构建文件的完整路径

# 获取系统架构
sys_str = platform.machine()

# 初始化颜色配置colorama
init(autoreset=True)

# 定义全局变量

# 判断是否为dark mode
is_dark_mode = False
if os.name == 'posix':  # linux
    if 'TERM_PROGRAM' in os.environ and os.environ['TERM_PROGRAM'] == 'iTerm.app':
        # iTerm2 终端
        is_dark_mode = os.popen('defaults read com.googlecode.iterm2 "Effective Color Profile"').read().strip() == 'Dark'
    else:
        # 其他终端
        is_dark_mode = os.getenv('COLORTERM') == 'truecolor' or os.getenv('TERM') in ['eterm-color', 'xterm-256color']
elif os.name == 'nt':  # windows系统
    from ctypes import windll, byref
    def get_current_color():
        handle = windll.kernel32.GetStdHandle(-11)
        csbi = CONSOLE_SCREEN_BUFFER_INFO()
        windll.kernel32.GetConsoleScreenBufferInfo(handle, byref(csbi))
        return csbi.wAttributes
    is_dark_mode = get_current_color() >> 4 in [0, 1, 2, 8, 9, 10]

# 定义颜色常量
if is_dark_mode:
    COLOR_RED = Fore.RED
    COLOR_GREEN = Fore.GREEN
    COLOR_YELLOW = Fore.YELLOW
    COLOR_BLUE = Fore.BLUE
    COLOR_MAGENTA = Fore.MAGENTA
    COLOR_CYAN = Fore.CYAN
    COLOR_WHITE = Fore.WHITE
    COLOR_NONE = Style.RESET_ALL
else:
    COLOR_RED = Style.BRIGHT + Fore.RED
    COLOR_GREEN = Style.BRIGHT + Fore.GREEN
    COLOR_YELLOW = Style.BRIGHT + Fore.YELLOW
    COLOR_BLUE = Style.BRIGHT + Fore.BLUE
    COLOR_MAGENTA = Style.BRIGHT + Fore.MAGENTA
    COLOR_CYAN = Style.BRIGHT + Fore.CYAN
    COLOR_WHITE = Style.BRIGHT + Fore.WHITE
    COLOR_NONE = Style.RESET_ALL

# 获取当前用户的用户名并作为全局变量
this_user = os.getenv('USER')
# 获取当前进程的登录名--大概是普通用户吧
local_user = os.environ.get('USER')
# 普通用户的桌面
user_home = f"/home/{local_user}/桌面"

# 按任意键继续
def get_pause():
    input("\n按任意键继续...")

# 定义清屏变量
CLEAR_SCREEN = {
    'clear': lambda: os.system('cls' if os.name=='nt' else 'clear')
}

# 定义时间变量
time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')

# 定义密码
global my_password
my_password = None

def change_to_root():
    global my_password
    if my_password is None:
        my_password = getpass.getpass("请 输 入 开 机 密 码：")
    return my_password

def run_sudo_command(command):
    if os.path.isfile(file_path):
        password = myown_passwd
    else:
        password = change_to_root()
    subprocess.run(["sudo", "-S", command], input=f"{password}\n", shell=False, capture_output=True, text=True)

# 回到主函数
def return_to_previous_menu():
    pass

# 定义头及选项
def print_head(head):
    for option in head:
        print(f"{COLOR_BLUE}{option}{COLOR_NONE}\n")

def print_menu_options(menu_options):
    print(f"""{COLOR_GREEN} + 0. {COLOR_RED}按 0 退出{COLOR_NONE}\n""")
    for index, option in enumerate(menu_options, start=1):
        print(f"{COLOR_GREEN} + {index}. {COLOR_RED}按 {index} {option}{COLOR_NONE}\n")
    print(f"""温馨提示:如果你不想执行选项...按{COLOR_MAGENTA} 0 {COLOR_NONE}或者 {COLOR_MAGENTA} Ctrl + C {COLOR_NONE}即可退出\n""")

def select_menu(menu_dict):
    while True:
        choose = input("请选择菜单 [0-{}]: ".format(len(menu_dict)-1))
        if not choose.strip():
            exit(1)
        elif choose == '0':
            return
        elif choose in menu_dict:
            menu_dict[choose]()
            print(os.getuid())
            break
        else:
            print("无效的选择")

# 获取当前网卡名
def get_active_network_interface():
    interfaces = psutil.net_if_stats().keys()
    for interface in interfaces:
        if interface != 'lo' and netifaces.AF_INET in netifaces.ifaddresses(interface):
            return interface
    return None

# 获取当前正在使用的网卡名称
active_interface = get_active_network_interface()


def print_options(options):
    for key, value in options.items():
        print(f"{key}: {value}")
